import {
	Controller,
	Get,
	Post,
	Body,
	Patch,
	Param,
	Delete,
	Query,
	UseGuards,
} from "@nestjs/common";
import {
	ApiTags,
	ApiOperation,
	ApiParam,
	ApiQuery,
	ApiResponse,
} from "@nestjs/swagger";
import { ProductService } from "./product.service";
import { CreateProductDto } from "./dto/create-product.dto";
import { UpdateProductDto } from "./dto/update-product.dto";
import { ProductSpec } from "./entities/product-spec.entity";
import { ProductSku } from "./entities/product-sku.entity";
import { CreateProductSpecDto } from "./dto/create-product-spec.dto";
import { CreateProductSkuDto } from "./dto/create-product-sku.dto";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../auth/roles.guard";
import { Roles } from "../auth/roles.decorator";

@ApiTags("商品")
@Controller("products")
export class ProductController {
	constructor(private readonly productService: ProductService) {}

	@Post("create")
	@ApiOperation({ summary: "创建商品" })
	@ApiResponse({ status: 201, description: "商品创建成功" })
	async create(@Body() createProductDto: CreateProductDto) {
		// 先处理图片
		try {
			const processedDto = (await this.processImage(
				createProductDto
			)) as CreateProductDto;
			const product = await this.productService.create(processedDto);
			return {
				code: 200,
				data: product,
				message: "商品创建成功",
			};
		} catch (error) {
			throw error;
		}
	}

	@Get("list")
	@ApiOperation({ summary: "获取商品列表" })
	@ApiQuery({ name: "page", required: false, description: "页码" })
	@ApiQuery({ name: "limit", required: false, description: "每页条数" })
	@ApiQuery({ name: "name", required: false, description: "商品名称" })
	@ApiQuery({ name: "category", required: false, description: "商品分类" })
	@ApiQuery({ name: "status", required: false, description: "商品状态" })
	@ApiQuery({
		name: "sort",
		required: false,
		description: "排序字段，支持price(积分)和createdAt(上架时间)",
	})
	@ApiQuery({
		name: "order",
		required: false,
		description: "排序方向，asc(升序)或desc(降序)",
	})
	@ApiResponse({ status: 200, description: "获取商品列表成功" })
	async findAll(
		@Query()
		query: {
			page?: string;
			limit?: string;
			name?: string;
			category?: string;
			status?: string;
			sort?: string;
			order?: "asc" | "desc";
		}
	) {
		try {
			const [products, total] = await this.productService.findAll(query);
			return {
				code: 200,
				data: {
					list: products,
					total,
					page: +query.page || 1,
					limit: +query.limit || 10,
				},
				message: "获取商品列表成功",
			};
		} catch (error) {
			// 如果是已知的BadRequestException，保留其状态码
			if (error.status === 400) {
				throw error;
			}
			// 服务器错误
			return {
				code: 500,
				message: "获取商品列表失败: " + error.message,
			};
		}
	}

	@Get("findOne/:id")
	@ApiOperation({ summary: "获取商品详情" })
	@ApiParam({ name: "id", description: "商品ID" })
	@ApiResponse({ status: 200, description: "获取商品详情成功" })
	@ApiResponse({ status: 404, description: "商品不存在" })
	async findOne(@Param("id") id: string) {
		const product = await this.productService.findOne(+id);

		// 添加日志查看规格和SKU数据
		console.log(
			`产品 ID: ${id} 的规格数量:`,
			product.specs ? product.specs.length : 0
		);
		if (product.specs && product.specs.length > 0) {
			console.log("商品规格示例:", product.specs[0]);
		}
		console.log(
			`产品 ID: ${id} 的SKU数量:`,
			product.skus ? product.skus.length : 0
		);

		return {
			code: 200,
			data: product,
			message: "获取商品详情成功",
		};
	}

	@Patch("update/:id")
	@ApiOperation({ summary: "更新商品" })
	@ApiParam({ name: "id", description: "商品ID" })
	@ApiResponse({ status: 200, description: "商品更新成功" })
	@ApiResponse({ status: 404, description: "商品不存在" })
	async update(
		@Param("id") id: string,
		@Body() updateProductDto: UpdateProductDto
	) {
		// 先处理图片
		try {
			const processedDto = (await this.processImage(
				updateProductDto
			)) as UpdateProductDto;
			const product = await this.productService.update(+id, processedDto);
			return {
				code: 200,
				data: product,
				message: "商品更新成功",
			};
		} catch (error) {
			throw error;
		}
	}

	@Delete("delete/:id")
	@ApiOperation({ summary: "删除商品" })
	@ApiParam({ name: "id", description: "商品ID" })
	@ApiResponse({ status: 200, description: "商品删除成功" })
	@ApiResponse({ status: 404, description: "商品不存在" })
	async remove(@Param("id") id: string) {
		await this.productService.remove(+id);
		return {
			code: 200,
			message: "商品删除成功",
		};
	}

	@Post("batch")
	@ApiOperation({ summary: "批量获取商品详情" })
	@ApiResponse({ status: 200, description: "批量获取商品详情成功" })
	async batchGetProducts(@Body() data: { ids: number[] }) {
		if (!data.ids || !Array.isArray(data.ids) || data.ids.length === 0) {
			return {
				code: 400,
				message: "请提供有效的商品ID列表",
			};
		}

		try {
			const products = await Promise.all(
				data.ids.map((id) => this.productService.findOne(id).catch(() => null))
			);

			// 过滤掉不存在的商品
			const validProducts = products.filter((product) => product !== null);

			return {
				code: 200,
				data: validProducts,
				message: "批量获取商品详情成功",
			};
		} catch (error) {
			return {
				code: 500,
				message: "批量获取商品详情失败: " + error.message,
			};
		}
	}

	// 处理图片的方法
	private async processImage(
		dto: CreateProductDto | UpdateProductDto
	): Promise<CreateProductDto | UpdateProductDto> {
		// 如果有图片数据
		if ("imageUrl" in dto && dto.imageUrl) {
			// 处理图片数据
			const processedImage = await this.productService.processProductImage(
				dto.imageUrl
			);
			// 如果图片处理成功，则更新image字段并移除imageUrl字段
			if (processedImage) {
				dto.image = processedImage;
				// @ts-ignore - 由于TypeScript不能确定dto是否有imageUrl属性
				delete dto.imageUrl;
			}
		}
		return dto;
	}

	// 商品规格相关接口
	@Post(":id/specs")
	@UseGuards(JwtAuthGuard)
	async createSpec(
		@Param("id") productId: string,
		@Body() createProductSpecDto: CreateProductSpecDto
	) {
		try {
			// 确保规格关联到正确的商品
			createProductSpecDto.productId = +productId;
			const spec = await this.productService.createSpec(createProductSpecDto);
			return {
				code: 200,
				data: spec,
				message: "商品规格创建成功",
			};
		} catch (error) {
			return {
				code: 500,
				message: "商品规格创建失败: " + error.message,
			};
		}
	}

	@Get(":id/specs")
	async getProductSpecs(@Param("id") productId: string) {
		try {
			const specs = await this.productService.getProductSpecs(+productId);

			// 添加日志
			console.log(
				`获取产品 ID: ${productId} 的规格数量:`,
				specs ? specs.length : 0
			);
			console.log("查询条件:", { productId: +productId });
			if (specs && specs.length > 0) {
				console.log("规格示例:", specs[0]);
			} else {
				console.log("未找到规格数据");
			}

			return {
				code: 200,
				data: specs,
				message: "获取商品规格成功",
			};
		} catch (error) {
			console.error("获取规格错误:", error);
			return {
				code: 500,
				message: "获取商品规格失败: " + error.message,
			};
		}
	}

	@Delete("specs/:id")
	@UseGuards(JwtAuthGuard)
	async deleteSpec(@Param("id") id: string) {
		try {
			await this.productService.deleteSpec(+id);
			return {
				code: 200,
				message: "删除商品规格成功",
			};
		} catch (error) {
			return {
				code: 500,
				message: "删除商品规格失败: " + error.message,
			};
		}
	}

	// 商品SKU相关接口
	@Post(":id/skus")
	@UseGuards(JwtAuthGuard)
	async createSku(
		@Param("id") productId: string,
		@Body() createProductSkuDto: CreateProductSkuDto
	) {
		try {
			// 确保SKU关联到正确的商品
			createProductSkuDto.productId = +productId;
			const sku = await this.productService.createSku(createProductSkuDto);
			return {
				code: 200,
				data: sku,
				message: "商品SKU创建成功",
			};
		} catch (error) {
			return {
				code: 500,
				message: "商品SKU创建失败: " + error.message,
			};
		}
	}

	@Get(":id/skus")
	async getProductSkus(@Param("id") productId: string) {
		try {
			const skus = await this.productService.getProductSkus(+productId);
			return {
				code: 200,
				data: skus,
				message: "获取商品SKU成功",
			};
		} catch (error) {
			return {
				code: 500,
				message: "获取商品SKU失败: " + error.message,
			};
		}
	}

	@Get("skus/:id")
	async getSku(@Param("id") id: string) {
		try {
			const sku = await this.productService.getSku(+id);
			return {
				code: 200,
				data: sku,
				message: "获取SKU详情成功",
			};
		} catch (error) {
			return {
				code: 500,
				message: "获取SKU详情失败: " + error.message,
			};
		}
	}

	@Patch("skus/:id")
	@UseGuards(JwtAuthGuard)
	async updateSku(
		@Param("id") id: string,
		@Body() updateProductSkuDto: CreateProductSkuDto
	) {
		try {
			const sku = await this.productService.updateSku(+id, updateProductSkuDto);
			return {
				code: 200,
				data: sku,
				message: "更新SKU成功",
			};
		} catch (error) {
			return {
				code: 500,
				message: "更新SKU失败: " + error.message,
			};
		}
	}

	@Delete("skus/:id")
	@UseGuards(JwtAuthGuard)
	async deleteSku(@Param("id") id: string) {
		try {
			await this.productService.deleteSku(+id);
			return {
				code: 200,
				message: "删除SKU成功",
			};
		} catch (error) {
			return {
				code: 500,
				message: "删除SKU失败: " + error.message,
			};
		}
	}

	// 修复商品规格数据
	@Get("fix-specs")
	async fixProductSpecs() {
		try {
			await this.productService.fixProductSpecs();
			return {
				code: 200,
				message: "商品规格数据修复完成",
			};
		} catch (error) {
			console.error("修复规格数据错误:", error);
			return {
				code: 500,
				message: "修复商品规格数据失败: " + error.message,
			};
		}
	}
}
